/**
 * @description 输入框事件模板
 * @example 资产比例变化
 * @author muisuidaan
 */

import styled from "styled-components";

import SInput from "../Input";
import { Fragment, useEffect, useState } from "react";
import { RedBtn } from "../Button";
import { BottomCard } from "./BottomCard";
import { RedTitle } from "../Title/redTitile";
import SInputNumber from "../Input/InputNumber";
import {
  ToFixNumber,
  IsExitUnit,
  UNIT_LIST,
  UNIT_LIST_FLECT,
} from "@/utils/utils";
import { collectErrors } from './InlineInput'


// 适合此模板的事件代码
export const EVENT_INLINE_INPUT = [
  "portfolio_industry_concentration_sw", // 行业集中度（申万）-组合
  "portfolio_industry_concentration_zz", //行业集中度（中证）-组合
  // "portfolio_section_concentration_zz", //板块集中度-组合
  "portfolio_asset_allocation_alert", //资产比例变化-组合
  
  "fund_profit_risk2",//"货基风险提醒二"
  
];

const PLACEHOLDER_1 = ["组合第一大行业占比＞", "组合前三大行业占比＞"];
const PLACEHOLDER_2 = ["%", "%"];

const EVENT_INLINE_MAP = {
  portfolio_industry_concentration_sw: {
    key1: "topOneIndustryThreshold",
    key2: "topThreeIndustryThreshold",
    text_value1:PLACEHOLDER_1[0],
    text_value3:PLACEHOLDER_1[1].slice(2,PLACEHOLDER_1[1].length),
    value1: PLACEHOLDER_1[0],
    value2: PLACEHOLDER_2[0],
    value3: PLACEHOLDER_1[1],
    value4: PLACEHOLDER_2[1],
    bridge:'或'
  },
  portfolio_industry_concentration_zz: {
    key1: "topOneIndustryThreshold",
    key2: "topThreeIndustryThreshold",
    text_value1:PLACEHOLDER_1[0],
    text_value3:PLACEHOLDER_1[1].slice(2,PLACEHOLDER_1[1].length),
    value1: PLACEHOLDER_1[0],
    value2: PLACEHOLDER_2[0],
    value3: PLACEHOLDER_1[1],
    value4: PLACEHOLDER_2[1],
    bridge:'或'

  },
  // portfolio_section_concentration_zz: {
  //   key1: "heavyStock",
  //   key2: "oneMThreshold",
  //   key3: "threeMThreshold",
  //   value1: PLACEHOLDER_1[0],
  //   value2: PLACEHOLDER_2[0],
  // },
  portfolio_asset_allocation_alert: {
    key1: "stockThreshold",
    key2: "bondThreshold",
    title1: "股票",
    title2: "债券",
    text_value1:"资产比例与阈值差异在",
    text_value3:"资产比例与阈值差异在",
    value1: "阈值为比例上下限的正负",
    table: {},
    value2: PLACEHOLDER_2[0],
    value3: "阈值为比例上下限的正负",
    value4: PLACEHOLDER_2[1],
    bridge:'；'

  },
  
  fund_profit_risk2: {
    key1: "riskThreshold2Max",
    key2: "riskThreshold2Avg",
    text_value1:'基金披露的偏离度最小值<0，偏离度最大值在同类基金所在排名（从小到大）分位前',
    text_value3:'偏离度绝对值平均值在同类基金所在排名（从大到小）分位前',
    value1: '基金披露的偏离度最小值<0，偏离度最大值在同类基金所在排名（从小到大）分位前',
    value2: PLACEHOLDER_2[0],
    value3:'偏离度绝对值平均值在同类基金所在排名（从大到小）分位前',
    value4: PLACEHOLDER_2[1],
    bridge:' ，'
  },
};
const Box = styled.div`
  width: 100%;
  background: #ffffff;
  border: 1px solid #e4e4e4;
  border-radius: 2px;
  padding: 12px;
  color: #35425e;
  margin-top: 8px;
`;
export const FlexDiv = styled.div`
  display: flex;
  align-items: center;
  margin-top: ${(props) => props.mt || "0"};
  span {
    em {
      font-style: normal;
      font-weight: 600;
    }
  }
`;
const EventTableWrapper = styled.div`
  margin-bottom: 24px;
  table {
    border: 1px solid #d4d7dd;
  }
  th {
    background: #f5f6f9;
    text-align: center;
    font-weight: 600;
    font-size: 13px;
    color: #35425e;
    line-height: 28px;
    border-left: 1px solid #d4d7dd;
  }

  td:nth-child(2n + 1) {
    color: #e64a00;
    font-weight: 600;
  }
  td:nth-child(1) {
    background: #f5f6f9;
    /* padding: 0 16px; */
    font-weight: 600;
    width: 58px;
    color: #35425e;
  }
  td {
    background: #fff;
    /* padding: 0 21px; */
    text-align: center;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    font-size: 13px;
    color: #35425e;
    line-height: 28px;
    width: 96px;
    border-top: 1px solid #d4d7dd;
    border-left: 1px solid #d4d7dd;
  }
`;
const EventTable = ({saveParams}) => {
  const {stockUpperBound,stockLowerBound,stockThreshold,bondUpperBound,bondLowerBound,bondThreshold} = saveParams||{};
  return (
    <EventTableWrapper>
      <p className="title">当前资产比例阈值：</p>
      <table>
        <thead>
          <tr>
            <th></th>
            <th>设定上限</th>
            <th>触发上限阈值</th>
            <th>设定下限</th>
            <th>触发下限阈值</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>股票</td>
            <td>{(stockUpperBound||stockUpperBound===0)&&ToFixNumber(stockUpperBound,2,true)?ToFixNumber(stockUpperBound,2,true)+'%':'-'}</td>
            <td>{(stockUpperBound||stockUpperBound===0)&&ToFixNumber((Number(stockUpperBound)+Number(stockThreshold)),2,true)?ToFixNumber((Number(stockUpperBound)*(1-Number(stockThreshold/100))),2,true)+'%':'-'}</td>
            <td>{(stockLowerBound||stockLowerBound===0)&&ToFixNumber(stockLowerBound,2,true)?ToFixNumber(stockLowerBound,2,true)+'%':'-'}</td>
            <td>{(stockLowerBound||stockLowerBound===0)&&ToFixNumber((Number(stockLowerBound)-Number(stockThreshold)),2,true)?ToFixNumber((Number(stockLowerBound)*(1+Number(stockThreshold/100))),2,true)+'%':'-'}</td>
            
          </tr>
          <tr>
            <td>债券</td>
            <td>{(bondUpperBound||bondUpperBound===0)&&ToFixNumber(bondUpperBound,2,true)?ToFixNumber(bondUpperBound,2,true)+'%':'-'}</td>
            <td>{(bondUpperBound||bondUpperBound===0)&&ToFixNumber((Number(bondUpperBound)*(1-Number(bondThreshold/100))),2,true)?ToFixNumber((Number(bondUpperBound)*(1-Number(bondThreshold/100))),2,true)+'%':'-'}</td>
            <td>{(bondLowerBound||bondLowerBound===0)&&ToFixNumber(bondUpperBound,2,true)?ToFixNumber(bondLowerBound,2,true)+'%':'-'}</td>
            <td>{(bondLowerBound||bondLowerBound===0)&&ToFixNumber((Number(bondLowerBound)*(1+Number(bondThreshold/100))),2,true)?ToFixNumber((Number(bondLowerBound)*(1+Number(bondThreshold/100))),2,true)+'%':'-'}</td>
            

            {/* <td>{bondUpperBound||bondUpperBound===0?Number(bondUpperBound).toFixed(2)+'%':'-'}</td>
            <td>{bondUpperBound||bondUpperBound===0?(Number(bondUpperBound)+Number(bondThreshold)).toFixed(2)+'%':'-'}</td>
            <td>{bondLowerBound||bondLowerBound===0?Number(bondLowerBound).toFixed(2)+'%':'-'}</td>
            <td>{bondLowerBound||bondLowerBound===0?(Number(bondLowerBound)-Number(bondThreshold)).toFixed(2)+'%':'-'}</td>
            */}
          </tr>
        </tbody>
      </table>
    </EventTableWrapper>
  );
}
const RowMultipleInput = (props: any) => {
  console.log("props", props);
  const { thresholdValue, onSubmit, eventInfo, enable } = props;
  const { value = "portfolio_asset_allocation_alert" } = eventInfo || {};

  const [saveParams, setSaveParams] = useState({ ...thresholdValue });

  const [isChanged, setIsChanged] = useState(false);
  const [errorList, setErrorList] = useState([]);

  useEffect(() => {
    setSaveParams({
      ...thresholdValue,
    });
    setErrorList([])
    setIsChanged(false);
  }, [thresholdValue]);

  useEffect(() => {
    if(enable !== undefined && enable !== eventInfo?.enable) {
      setIsChanged(true)
    }
  },[enable])

  const onChange = (val: string | number | null, key: string) => {
    handleCollectErrors(val?.toString(), key);
    setIsChanged(true);
    setSaveParams((state) => {
      return {
        ...state,
        [key]: val || "",
      };
    });
  };

  // 收集错误
  const handleCollectErrors = (val?: string, key?: string) => {
    let res: string[] = collectErrors(val, key, errorList, saveParams)
    setErrorList([...new Set(res)])
    return [...new Set(res)];
  }

  const onClick = () => {
    const res = handleCollectErrors();
    console.log("res", res, errorList.length > 0 || res.length > 0);

    if (errorList.length > 0 || res.length > 0|| !isChanged) return;
    const preValues = {...saveParams};
    /*后端要求股票债券上下限不需要传回*/
    delete preValues["f"];
    delete preValues["stockUpperBound"];
    delete preValues["bondLowerBound"];
    delete preValues["bondUpperBound"];

    onSubmit({
      id: parseFloat(eventInfo.key),
      preValue: preValues,
      dataMemo: createInfoText(false),
    });
  };
  console.log(errorList);

  //通过参数生成说明文案
  const createInfoText = (html: boolean) => {
    if(eventInfo?.value==="portfolio_asset_allocation_alert")return null;
    let str = `<p>* ${EVENT_INLINE_MAP[value]?.title1||''}${EVENT_INLINE_MAP[value]?.text_value1}<em> ${
      ToFixNumber(saveParams[EVENT_INLINE_MAP[value]?.key1])
    }${EVENT_INLINE_MAP[value]?.value2} </em>${EVENT_INLINE_MAP[value]?.bridge||''}${EVENT_INLINE_MAP[value]?.title2||''}${
      EVENT_INLINE_MAP[value]?.text_value3
    }<em> ${ToFixNumber(saveParams[EVENT_INLINE_MAP[value]?.key2])}${
      EVENT_INLINE_MAP[value]?.value4
    } </em>。</p>`;
    if (!html) {
      str = str
        .replaceAll("<p>", "")
        .replaceAll("</p>", "")
        .replaceAll("<em>", "")
        .replaceAll("</em>", "")
        .replace(/\s+/g,"")
    }

    return str;
  };

  return (
    <Fragment>
      <Box>
        <FlexDiv>
          <span>
            {EVENT_INLINE_MAP[value]?.title1 && (
              <em> {EVENT_INLINE_MAP[value]?.title1} </em>
            )}
            {EVENT_INLINE_MAP[value]?.value1}
          </span>
          <SInputNumber
            value={saveParams[EVENT_INLINE_MAP[value]?.key1]}
            isError={errorList.includes(EVENT_INLINE_MAP[value]?.key1)}
            onChange={(e) =>
              onChange(e, EVENT_INLINE_MAP[value]?.key1)
            }
            min={
              UNIT_LIST_FLECT[
                IsExitUnit(EVENT_INLINE_MAP[value]?.value2, UNIT_LIST)
              ]?.min
            }
            max={
              UNIT_LIST_FLECT[
                IsExitUnit(EVENT_INLINE_MAP[value]?.value2, UNIT_LIST)
              ]?.max
            }
            precision={
              UNIT_LIST_FLECT[
                IsExitUnit(EVENT_INLINE_MAP[value]?.value2, UNIT_LIST)
              ]?.count
            }
            // unit={IsExitUnit(EVENT_INLINE_MAP[value]?.value2, UNIT_LIST)}
            // step={
            //   UNIT_LIST_FLECT[
            //     IsExitUnit(EVENT_INLINE_MAP[value]?.value2, UNIT_LIST)
            //   ]?.step
            // }
            // controls={false}
            // stringMode
            // formatter={(val) => {
            //   const count =
            //     UNIT_LIST_FLECT[
            //       IsExitUnit(EVENT_INLINE_MAP[value]?.value2, UNIT_LIST)
            //     ]?.count;

            //   return parseFloat(val).toFixed(count);
            // }}
            // parser={(val) => {
            //   const count =
            //     UNIT_LIST_FLECT[
            //       IsExitUnit(EVENT_INLINE_MAP[value]?.value2, UNIT_LIST)
            //     ]?.count;
            //   return parseFloat(val).toFixed(count);
            // }}
          />
          {/* <SInput
            style={{ width: 80, margin: "0 8px", padding: "0 8px" }}
            value={saveParams[EVENT_INLINE_MAP[value]?.key1]}
            isError={errorList.includes(EVENT_INLINE_MAP[value]?.key1)}
            onChange={(e) =>
              onChange(e.target.value, EVENT_INLINE_MAP[value]?.key1)
            }
          /> */}
          <span>{EVENT_INLINE_MAP[value]?.value2}</span>
        </FlexDiv>
        <FlexDiv mt="8px">
          <span>
            {EVENT_INLINE_MAP[value]?.title2 && (
              <em> {EVENT_INLINE_MAP[value]?.title2} </em>
            )}
            {EVENT_INLINE_MAP[value]?.value3}
          </span>
          <SInputNumber
            value={saveParams[EVENT_INLINE_MAP[value]?.key2]}
            isError={errorList.includes(EVENT_INLINE_MAP[value]?.key2)}
            onChange={(e) =>
              onChange(e, EVENT_INLINE_MAP[value]?.key2)
            }
            min={
              UNIT_LIST_FLECT[
                IsExitUnit(EVENT_INLINE_MAP[value]?.value4, UNIT_LIST)
              ]?.min
            }
            max={
              UNIT_LIST_FLECT[
                IsExitUnit(EVENT_INLINE_MAP[value]?.value4, UNIT_LIST)
              ]?.max
            }
            precision={
              UNIT_LIST_FLECT[
                IsExitUnit(EVENT_INLINE_MAP[value]?.value4, UNIT_LIST)
              ]?.count
            }
            // unit={IsExitUnit(EVENT_INLINE_MAP[value]?.value4, UNIT_LIST)}
            // step={
            //   UNIT_LIST_FLECT[
            //     IsExitUnit(EVENT_INLINE_MAP[value]?.value4, UNIT_LIST)
            //   ]?.step
            // }
            // controls={false}
            // stringMode
            // formatter={(val) => {
            //   const count =
            //     UNIT_LIST_FLECT[
            //       IsExitUnit(EVENT_INLINE_MAP[value]?.value4, UNIT_LIST)
            //     ]?.count;

            //   return parseFloat(val).toFixed(count);
            // }}
            // parser={(val) => {
            //   const count =
            //     UNIT_LIST_FLECT[
            //       IsExitUnit(EVENT_INLINE_MAP[value]?.value4, UNIT_LIST)
            //     ]?.count;
            //   return parseFloat(val).toFixed(count);
            // }}
          />
          {/* <SInput
              style={{ width: 80, margin: "0 8px", padding: "0 8px" }}
              value={saveParams[EVENT_INLINE_MAP[value]?.key1]}
              isError={errorList.includes(EVENT_INLINE_MAP[value]?.key1)}
              onChange={(e) =>
                onChange(e.target.value, EVENT_INLINE_MAP[value]?.key1)
              }
            /> */}
          <span>{EVENT_INLINE_MAP[value]?.value4}</span>
        </FlexDiv>
        {/* 底部说明文案 */}
        <BottomCard
          info={createInfoText(true)}
          table={EVENT_INLINE_MAP[value]?.table ? <EventTable saveParams={saveParams}/> : null}
        ></BottomCard>
      </Box>
      <FlexDiv style={{ marginTop: 12, alignItems: "flex-end" }}>
        <RedBtn disabled={!isChanged} onClick={onClick}>
          确定
        </RedBtn>
        {/* 按钮说明文案 */}
        {isChanged && <RedTitle eventInfo={eventInfo}></RedTitle>}
      </FlexDiv>
    </Fragment>
  );
};

export default RowMultipleInput;
